import { defineStore, type StateTree } from "pinia";
import router from "@/router";

interface Tab {
  title: string;
  id: string;
  fixed?: boolean;
}
interface Tabs {
  tabs: Map<string, Tab>;
  activeTab: string;
}
export const useTabsStore = defineStore("tabs", {
  state: (): Tabs => ({
    tabs: new Map<string, Tab>(),
    activeTab: "",
  }),
  getters: {
    getTabs: (state): Tab[] => {
      const a = state.tabs;
      // console.log(a);
      return Array.from(state.tabs.values());
    },
  },
  actions: {
    /**
     * 添加一个tab
     */
    async addTab(tab: Tab) {
      if (!this.tabs.has(tab.id)) {
        this.tabs.set(tab.id, tab);
      }
      this.switchTab(tab.id);
    },
    /**
     * 删除一个tab
     * @param tabId
     */
    async deleteTab(tabId: string) {
      if (tabId === this.activeTab) {
        const list = this.getTabs;
        let index = 0;
        const length = list.length;
        if (length > 2) {
          index = length - 2;
        }
        let flag = false;
        for (let i = 0; i < length; i++) {
          if (flag) {
            index = i;
            break;
          }
          if (list[i].id === tabId) {
            flag = true;
          }
        }
        // 切换到这个tab上
        await this.switchTab(list[index].id);
      }
      this.tabs.delete(tabId);
    },
    /**
     * 切换tab
     * @param tabId
     */
    async switchTab(tabId: string) {
      this.activeTab = tabId;
      await router.push(tabId);
    },

    /**
     * 设置tabs
     * @param tabs
     */
    setTabs(tabs: Tab[]) {
      this.tabs.clear();
      tabs.forEach((tab) => {
        this.tabs.set(tab.id, tab);
      });
    },
    /**
     * 清空tabs
     */
    clearTabs() {
      this.tabs.clear();
      this.activeTab = "";
    },
  },
  persist: {
    // 自定义序列化
    serializer: {
      deserialize: (value: string): StateTree => {
        // 把字符串转成state,其中tabs是map类型
        const obj = JSON.parse(value);
        const tabs = new Map<string, Tab>();
        obj.tabs.forEach((element: [string, Tab]) => {
          tabs.set(element[0], element[1]);
        });
        obj.tabs = tabs;
        return obj;
      },
      serialize: (value: StateTree): string => {
        // 把state 里的对象转成普通对象,把tabs转成普通对象,再转成字符串
        const obj: any = {};
        for (const key in value) {
          if (value.hasOwnProperty(key)) {
            const element = value[key];
            if (element instanceof Map) {
              obj[key] = Array.from(element);
            } else {
              obj[key] = element;
            }
          }
        }
        return JSON.stringify(obj);
      },
    },
    debug: true,
  },
});
